package com.ycx.furn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ycx.furn.bean.Furn;
import com.ycx.furn.bean.Msg;
import com.ycx.furn.service.FurnService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FurnController {
    @Resource
    private FurnService furnService;

    @PostMapping("/save")
    @ResponseBody
    public Msg save(@Validated @RequestBody Furn furn, Errors errors) {
        Map<String, Object> map = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        }

        if(map.isEmpty()){
            furnService.saveFurn(furn);
            return Msg.success();
        }else {
            return Msg.fail().addMsg("errorMsg", map);
        }

    }

    @RequestMapping("/list")
    @ResponseBody
    public Msg list() {
        List<Furn> furns = furnService.findAll();
        return Msg.success().addMsg("furns", furns);
    }

    @RequestMapping("/page")
    @ResponseBody
    public Msg listPage(@RequestParam(defaultValue = "1") Integer pageNum,
                        @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Furn> furnList = furnService.findAll();
        PageInfo<Object> pageInfo = new PageInfo<>(furnList, pageSize);

        return Msg.success().addMsg("pageInfo", pageInfo);
    }

    @RequestMapping("/update")
    @ResponseBody
    public Msg update(@RequestBody Furn furn) {
        furnService.update(furn);
        System.out.println("=============");
        return Msg.success();
    }

    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Msg delete(@PathVariable Integer id) {
        furnService.delete(id);
        System.out.println("======delete======id=" + id);
        return Msg.success();
    }

    @RequestMapping("/searchLike")
    @ResponseBody
    public Msg delete(String name, @RequestParam(defaultValue = "1") Integer pageNum,
                      @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Furn> furnList = furnService.findByCondition(name);
        PageInfo<Furn> pageInfo = new PageInfo<>(furnList, pageSize);
        return Msg.success().addMsg("pageInfo", pageInfo);
    }
}
